﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace SharpGen.Common
{
    public class SqlObjectCollection : ICollection<SqlObject>
    {
        private List<SqlObject> _internalCollection;
        
        public SqlObjectCollection()
        {
            _internalCollection = new List<SqlObject>();
        }

        public SqlObject this[string id]
        {
            get 
            {
                return GetItemByID(id);
            }
            set
            { 
                int idx = -1;
                SqlObject obj = GetItemByID(id, out idx);
                if (idx > -1)
                {
                    _internalCollection[idx] = value;
                }
            }
        }

        private SqlObject GetItemByID(string id)
        {
            int idx = -1;
            return GetItemByID(id, out idx);
        }

        private SqlObject GetItemByID(string id, out int index)
        {
            index = -1;
            for (int i = 0; i < _internalCollection.Count; i++)
            {
                if (_internalCollection[i].ID == id)
                {
                    index = i;
                    return _internalCollection[i];
                }

            }
            return null;
        }

        #region ICollection<SqlObject> Members

        public void Add(SqlObject item)
        {
            _internalCollection.Add(item);
        }        

        public void Clear()
        {
            _internalCollection.Clear();
        }

        public bool Contains(SqlObject item)
        {
            return _internalCollection.Contains(item);
        }

        public bool Contains(string id)
        {
            foreach (SqlObject obj in _internalCollection)
            {
                if (obj.ID == id)
                {
                    return true;
                }
            }
            return false;
        }

        public void CopyTo(SqlObject[] array, int arrayIndex)
        {
            _internalCollection.CopyTo(array, arrayIndex);
        }

        public int Count
        {
            get { return _internalCollection.Count; }
        }

        public bool IsReadOnly
        {
            get { return false; }
        }

        public bool Remove(SqlObject item)
        {
            return _internalCollection.Remove(item);
        }

        #endregion

        #region IEnumerable<SqlObject> Members

        public IEnumerator<SqlObject> GetEnumerator()
        {
            return _internalCollection.GetEnumerator();
        }

        #endregion

        #region IEnumerable Members

        IEnumerator IEnumerable.GetEnumerator()
        {
            return _internalCollection.GetEnumerator();
        }

        #endregion
    }
}
